{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import random\n",
    "import datetime\n",
    "import json\n",
    "import os\n",
    "\n",
    "# 设置数据存储的路径\n",
    "data_path = '/can_data'\n",
    "\n",
    "# 定义车辆状态\n",
    "vehicle_status = ['行驶中', '停车中', '充电中', '故障']\n",
    "\n",
    "# 定义充电状态\n",
    "charging_status = ['未充电', '正在充电']\n",
    "\n",
    "# 定义已生成的车架号\n",
    "vin_set = set()\n",
    "\n",
    "# 获取当前日期\n",
    "now = datetime.datetime.now()\n",
    "date_str = now.date().strftime('%Y-%m-%d')\n",
    "\n",
    "# 检查数据存储的路径是否存在，不存在则创建\n",
    "if not os.path.exists(data_path):\n",
    "    os.makedirs(data_path)\n",
    "\n",
    "# 检查当天的数据文件是否存在，不存在则创建\n",
    "data_file = os.path.join(data_path, f'{date_str}/can-{date_str}.json')\n",
    "if not os.path.exists(os.path.dirname(data_file)):\n",
    "    os.makedirs(os.path.dirname(data_file))\n",
    "\n",
    "if not os.path.exists(data_file):\n",
    "    with open(data_file, 'w') as f:\n",
    "        f.write('')\n",
    "\n",
    "\n",
    "# 打开当天的数据文件，确定写入位置\n",
    "with open(data_file, 'rb') as f:\n",
    "    f.seek(0, 2)    #接着使用f.seek(0, 2)将文件指针移动到文件结尾，即偏移量为0，相对模式为2（文件末尾）\n",
    "    file_size = f.tell()\n",
    "\n",
    "write_file_index = 0\n",
    "if file_size > 100 * 1024 * 1024:\n",
    "    write_file_index = file_size // (100 * 1024 * 1024)\n",
    "\n",
    "write_file = os.path.join(data_path, f'{date_str}/can-{date_str}.json.{write_file_index}')\n",
    "if not os.path.exists(write_file):\n",
    "    with open(write_file, 'w') as f:\n",
    "        f.write('')\n",
    "\n",
    "# 设置数据生成时间范围\n",
    "earliest_time = now - datetime.timedelta(days=10)\n",
    "\n",
    "# 生成车辆数据\n",
    "def generate_vehicle_data():\n",
    "    while True:\n",
    "        vin = ''.join(random.choices('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', k=17))\n",
    "        if vin not in vin_set:\n",
    "            vin_set.add(vin)\n",
    "            break\n",
    "    \n",
    "    mileage = round(random.uniform(10000, 50000), 2)\n",
    "    speed = round(random.uniform(0, 120), 2)\n",
    "    status = random.choice(vehicle_status)\n",
    "    charging = random.choice(charging_status)\n",
    "    soc = round(random.uniform(20, 100), 2)\n",
    "    soc_low_alarm = '是' if soc < 30 else '否'\n",
    "    \n",
    "    # 生成数据生成时间\n",
    "    if file_size == 0:\n",
    "        generate_time = earliest_time + datetime.timedelta(seconds=random.randint(0, 60 * 60 * 24))\n",
    "    else:\n",
    "        generate_time = now - datetime.timedelta(seconds=random.randint(0, 60 * 60 * 3))\n",
    "\n",
    "    generate_time_str = generate_time.strftime('%Y-%m-%d %H:%M:%S')\n",
    "    data = {\n",
    "        '车架号': vin,\n",
    "        '行驶总里程': mileage,\n",
    "        '车速': speed,\n",
    "        '车辆状态': status,\n",
    "        '充电状态': charging,\n",
    "        '剩余电量SOC': soc,\n",
    "        'SOC低报警': soc_low_alarm,\n",
    "        '数据生成时间': generate_time_str\n",
    "    }\n",
    "    \n",
    "    return data\n",
    "\n",
    "# 生成足够数量的车辆数据\n",
    "vehicle_data = []\n",
    "while len(vin_set) < 20:\n",
    "    vehicle_data.append(generate_vehicle_data())\n",
    "\n",
    "for i in range(300):\n",
    "    vehicle_data.append(generate_vehicle_data())\n",
    "\n",
    "# 随机添加一些重复数据\n",
    "repeat_indices = random.sample(range(len(vehicle_data)), 20)\n",
    "for i in repeat_indices:\n",
    "    data = {k:v for k,v in vehicle_data[i].items()}\n",
    "    data['数据生成时间'] = (datetime.datetime.strptime(data['数据生成时间'], '%Y-%m-%d %H:%M:%S') + datetime.timedelta(seconds=2)).strftime('%Y-%m-%d %H:%M:%S')\n",
    "    vehicle_data.insert(i+1, data)\n",
    "\n",
    "# 将数据写入文件\n",
    "with open(write_file, 'a') as f:\n",
    "    for data in vehicle_data:\n",
    "        json_data = json.dumps(data, ensure_ascii=False) + '\\n'\n",
    "        f.write(json_data)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.9.13 ('base')",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.13"
  },
  "orig_nbformat": 4,
  "vscode": {
   "interpreter": {
    "hash": "79c2bc36f36ebca92fe5f3c73355a3866f3a34a4fd0b1d43087d5313dd5fd5ff"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
